<?php

namespace App\Services\Admin\Order;

use App\Exceptions\OrderException;
use App\Helpers\MvcHelper;
use App\Models\Admin\User\UserUpdateOrderRecordsModel;
use App\Models\Applet\Order\SponsorOrderModel;
use Exception;
use Illuminate\Support\Facades\DB;

class SponsorOrderService extends BaseOrderService
{

    /**
     * 认养订单列表
     * @param array $params
     * @return array[]
     * @throws Exception
     */
    public function list(array $params): array
    {
        $total = $this->getSponsorOrderModel()->total($params);
        // 查询认养订单列表
        $sponsorOrderList = $this->getSponsorOrderModel()->list($params, [
            'sponsor_orders.id', 'nickname', 'phone', 'order_master_id', 'sponsor_orders.goods_id',
            'sponsor_orders.order_no', 'sponsor_orders.goods_price', 'sponsor_orders.total_price',
            'sponsor_orders.order_price', 'sponsor_orders.order_integral', 'sponsor_orders.quantity',
            'sponsor_orders.order_status', 'sponsor_orders.remark',
        ]);

        // 查询主订单列表
        $sponsorMasterOrderIds = array_column($sponsorOrderList, 'order_master_id');
        $sponsorMasterOrderList = $this->getSponsorMasterOrderModel()->getItemsByIds($sponsorMasterOrderIds, [
            'id', 'user_id', 'order_no', 'pay_type', 'pay_status', 'pay_time'
        ]);
        $sponsorMasterOrderListMap = array_column($sponsorMasterOrderList, null, 'id');

        $orderIds = array_column($sponsorOrderList, 'id');
        // 查询用户认养记录
        $userSponsorList = $this->getUserSponsorModel()->getItemsByOrderIds($orderIds, [
            'id', 'order_id'
        ]);

        $userSponsorListMap = array_column($userSponsorList, null, 'order_id');

        $list = [];
        foreach ($sponsorOrderList as $item) {
            $masterOrder = $sponsorMasterOrderListMap[$item['order_master_id']];
            $list[] = [
                'id' => $item['id'],
                'userName' => $item['nickname'],
                'phone' => $item['phone'],
                'orderMasterNo' => $masterOrder['order_no'],
                'orderNo' => $item['order_no'],
                'totalPrice' => $item['total_price'] / 100,
                'orderPrice' => $item['order_price'] / 100,
                'orderIntegral' => $item['order_integral'],
                'quantity' => $item['quantity'],
                'orderStatus' => $item['order_status'],
                'remark' => $item['remark'],
                'userSponsorId' => $userSponsorListMap[$item['id']]['id'] ?? 0
            ];
        }

        return [
            'list' => $list,
            'total' => $total
        ];
    }

    /**
     * 认养订单详情
     * @param array $params
     * @return array
     * @throws OrderException
     * @throws Exception
     */
    public function detail(array $params): array
    {
        // 查询认养订单
        $orderDetail = $this->getSponsorOrderModel()->getItemById($params['id'], [
            'id', 'order_master_id', 'goods_id', 'order_no', 'total_price',
            'order_price', 'order_integral', 'quantity', 'order_status'
        ]);
        if (empty($orderDetail)) {
            throw new OrderException('认养订单不存在', OrderException::CODE_1001);
        }

        // 查询主订单
        $masterOrderDetail = $this->getSponsorMasterOrderModel()->getItemById($orderDetail['order_master_id'], [
            'id', 'user_id', 'order_no', 'pay_type', 'pay_status', 'pay_time', 'remark'
        ]);

        // 查询订单商品
        $sponsorGoodsDetail = $this->getSponsorOrderGoodsModel()->getItemByOrderIdAndGoodsId($orderDetail['id'], $orderDetail['goods_id'], [
            'id', 'category_id', 'province_id', 'city_id', 'region_id', 'name', 'price', 'cover_img', 'start_time', 'cycle', 'params'
        ]);

        // 查询类型
        $sponsorCategoryDetail = $this->getSponsorCategoryModel()->getItemById($sponsorGoodsDetail['category_id'], [
            'id', 'title', 'img_url'
        ]);

        // 查询地区
        $areaIds = [$sponsorGoodsDetail['province_id'], $sponsorGoodsDetail['city_id'], $sponsorGoodsDetail['region_id']];
        $areaListData = $this->getAreaModel()->getAreaNameListByCodeList($areaIds);
        $areaList = [];
        foreach ($areaListData as $item) {
            $areaList[] = [
                'id' => $item['code'],
                'name' => $item['name'],
            ];
        }

        return [
            'id' => $orderDetail['id'],
            'orderMasterNo' => $masterOrderDetail['order_no'],
            'orderNo' => $orderDetail['order_no'],
            'totalPrice' => $orderDetail['total_price'] / 100,
            'orderPrice' => $orderDetail['order_price'] / 100,
            'orderIntegral' => $orderDetail['order_integral'],
            'quantity' => $orderDetail['quantity'],
            'orderStatus' => $orderDetail['order_status'],
            'payType' => $masterOrderDetail['pay_type'],
            'payStatus' => $masterOrderDetail['pay_status'],
            'remark' => $masterOrderDetail['remark'],
            'categoryInfo' => [
                'id' => $sponsorCategoryDetail['id'],
                'title' => $sponsorCategoryDetail['title'],
                'imgUrl' => $sponsorCategoryDetail['img_url'],
            ],
            'goodsInfo' => [
                'id' => $sponsorGoodsDetail['id'],
                'name' => $sponsorGoodsDetail['name'],
                'price' => $sponsorGoodsDetail['price'] / 100,
                'coverImg' => $sponsorGoodsDetail['cover_img'],
                'startTime' => $sponsorGoodsDetail['start_time'],
                'cycle' => $sponsorGoodsDetail['cycle'],
                'params' => $sponsorGoodsDetail['params']
            ],
            'areaList' => $areaList
        ];
    }

    /**
     * 更新订单状态
     * @return void
     * @throws OrderException
     * @throws Exception
     */
    public function update(array $params)
    {
        $sponsorOrder = $this->getSponsorOrderModel()->getItemById($params['id'], [
            'id', 'order_master_id', 'order_status', 'goods_id', 'order_status', 'quantity'
        ]);
        if (empty($sponsorOrder)) {
            throw new OrderException('认养订单不存在', OrderException::CODE_1001);
        }

        if ($sponsorOrder['order_status'] != SponsorOrderModel::ORDER_STATUS_WAIT) {
            throw new OrderException('状态不允许操作', OrderException::CODE_1002);
        }

        $sponsorOrderGoods = $this->getSponsorOrderGoodsModel()->getItemByOrderIdAndGoodsId($sponsorOrder['id'], $sponsorOrder['goods_id'], [
            'id', 'goods_id', 'province_id', 'city_id', 'region_id', 'name', 'price', 'cover_img', 'start_time', 'cycle', 'params',
        ]);

        $sponsorMasterOrder = $this->getSPonsorMasterOrderModel()->getItemById($sponsorOrder['order_master_id'], [
            'id', 'user_id',
        ]);

        $createSponsorData = [
            'user_id' => $sponsorMasterOrder['user_id'],
            'goods_id' => $sponsorOrder['goods_id'],
            'order_id' => $sponsorOrder['id'],
            'province_id' => $sponsorOrderGoods['province_id'],
            'city_id' => $sponsorOrderGoods['city_id'],
            'region_id' => $sponsorOrderGoods['region_id'],
            'name' => $sponsorOrderGoods['name'],
            'price' => $sponsorOrderGoods['price'],
            'cover_img' => $sponsorOrderGoods['cover_img'],
            'cycle' => $sponsorOrderGoods['cycle'],
            'start_time' => $sponsorOrderGoods['start_time'],
            'quantity' => $sponsorOrder['quantity'],
        ];


        DB::transaction(function () use ($params, $sponsorOrder, $createSponsorData) {
            // 更新订单状态
            $this->getSponsorOrderModel()->updateItemById($params['id'], [
                'order_status' => $params['orderStatus']
            ]);

            // 添加认养记录
            $this->getUserSponsorModel()->addItem($createSponsorData);

            // 添加手动更新订单记录
            $this->getUserUpdateOrderRecordsModel()->addItem([
                'type' => UserUpdateOrderRecordsModel::TYPE_SPONSOR_ORDER,
                'admin_user_id' => MvcHelper::getLoginUserId(),
                'order_id' => $params['id'],
                'old_order_status' => $sponsorOrder['order_status'],
                'new_order_status' => $params['orderStatus'],
                'remark' => $params['remark'],
            ]);
        });
    }
}
